package one.two.sixteen;

public class Rational {
	private long n;
	private long d;

	public Rational() {
		System.out.println("Can not be used by clients");
	}

	public Rational(int numerator, int denominator) {
		n = numerator;
		d = denominator;
		int g = gcd(numerator, denominator);
		if (g > 1) {
			n /= g;
			d /= g;
		}
	}

	private Rational(long numerator, long denominator) {
		n = numerator;
		d = denominator;
		long g = gcd(numerator, denominator);
		if (g > 1) {
			n /= g;
			d /= g;
		}
	}

	Rational plus(Rational b) {
		long newd = d * b.d;
		long newn = n * b.d + b.n * d;
		Rational r = new Rational(newn, newd);
		return r;
	}

	Rational minus(Rational b) {
		long newd = d * b.d;
		long newn = n * b.d - b.n * d;
		Rational r = new Rational(newn, newd);
		return r;
	}

	Rational times(Rational b) {
		long newd = d * b.d;
		long newn = n * b.n;
		Rational r = new Rational(newn, newd);
		return r;
	}

	Rational divedes(Rational b) {
		long newd = d * b.n;
		long newn = n * b.d;
		Rational r = new Rational(newn, newd);
		return r;
	}

	public boolean equals(Rational that) {
		if (that != null && d == that.d && n == that.n) {
			return true;
		}
		return false;
	}

	@Override
	public String toString() {
		if (n % d == 0) {
			return n / d + "";
		}
		return n + "/" + d;
	}

	private static int gcd(int a, int b) {
		if (a < b) {
			int t = a;
			a = b;
			b = t;
		}
		int r;
		do {
			r = a % b;
			a = b;
			b = r;
		} while (r != 0);
		return a;
	}

	private static long gcd(long a, long b) {
		if (a < b) {
			long t = a;
			a = b;
			b = t;
		}
		long r;
		do {
			r = a % b;
			a = b;
			b = r;
		} while (r != 0);
		return a;
	}

	public static long ad(long a, long b) {
		return a + b;
	}

	public static void main(String[] args) {
		Rational a = new Rational(1, 2);
		Rational b = new Rational(1, 2);
		Rational c = a.plus(b);
		System.out.println(c);
		System.out.println(Integer.MAX_VALUE);
	}

}
